from django.forms import model_to_dict
from django.http import HttpResponse, JsonResponse
import json

from django.views.decorators.cache import cache_page

from users import models
from utils.token import create_token, check_token
import random


def index(request):
    return HttpResponse("Hello, world. You're at the users index.")


def admin_login(request):
    try:
        if request.method == 'POST' and request.body:
            login_msg = json.loads(request.body)
            if login_msg.get("admin") and login_msg.get("password"):
                # 查找用户信息
                msg = models.AdminUser.objects.filter(admin_user=login_msg["admin"]).values()
                if len(msg):
                    admin_user = list(msg)[0]
                    # 检查密码
                    if admin_user["password"] == login_msg["password"]:
                        # 生成token 存入session
                        request.session["token"] = create_token(admin_user["id"], request.META.get("REMOTE_ADDR"), admin_user["permission_id"])
                        resp = JsonResponse({"state": 200, "message": "登录成功", "data": {}}, safe=False)
                        return resp
                    return JsonResponse({"state": 500, "message": "密码错误", "data": {}}, safe=False)
                else:
                    return JsonResponse({"state": 500, "message": "用户不存在", "data": {}}, safe=False)
            else:
                return JsonResponse({"state": 500, "message": "请输入账号或密码", "data": {}}, safe=False)
        else:
            return JsonResponse({"state": 500, "message": "错误请求", "data": {}}, safe=False)
    except Exception as ex:
        print("admin_login error")
        print(ex)
        return JsonResponse({"state": 500, "message": "服务器错误", "data": {}}, safe=False)


def common_login(request):
    try:
        if request.method == 'POST' and request.body:
            login_msg = json.loads(request.body)
            if login_msg.get("account") and login_msg.get("password"):
                msg = models.CommonUser.objects.filter(account=login_msg["account"]).values()
                if len(msg):
                    common_user = list(msg)[0]
                    if common_user["password"] == login_msg["password"]:
                        request.session["token"] = create_token(common_user["id"], request.META.get("REMOTE_ADDR"))
                        data = {
                            "account": common_user["account"],
                            "nickname": common_user["nickname"],
                            "icon": common_user["icon"]
                        }
                        resp = JsonResponse({"state": 200, "message": "登录成功", "data": data}, safe=False)
                        return resp
                    return JsonResponse({"state": 500, "message": "密码错误", "data": {}}, safe=False)
                else:
                    return JsonResponse({"state": 500, "message": "用户不存在", "data": {}}, safe=False)
            else:
                return JsonResponse({"state": 500, "message": "请输入账号或密码", "data": {}}, safe=False)
        else:
            return JsonResponse({"state": 500, "message": "错误请求", "data": {}}, safe=False)
    except Exception as ex:
        print("common_login error")
        print(ex)
        return JsonResponse({"state": 500, "message": "服务器错误", "data": {}}, safe=False)


def create_common_user(request):
    try:
        if request.method == 'POST' and request.body:
            register_msg = json.loads(request.body)
            if register_msg.get("account") and register_msg.get("password"):
                admin_user = 1  # 默认管理组
                if register_msg.get("admin_user"):
                    admin_user = register_msg["admin_user"]
                has_user = models.CommonUser.objects.filter(account=register_msg["account"]).values()
                if len(has_user):
                    return JsonResponse({"state": 500, "message": "账号已注册", "data": {}}, safe=False)
                else:
                    admin_msg = models.AdminUser.objects.get(id=admin_user)
                    if admin_msg:
                        new_user = {
                            "account": register_msg["account"],
                            "password": register_msg["password"],
                            "admin_group": admin_msg,
                            "nickname": "R#" + "".join(
                                random.sample(list('abcdefghijklmnopqrstuvwxyz1234567890!@#$%^&*'), 6))
                        }
                        user_info = models.CommonUser.objects.create(**new_user)
                        if not isinstance(user_info, dict):
                            if user_info.id:
                                return JsonResponse({"state": 200, "message": "注册成功", "data": {}}, safe=False)
                            else:
                                return JsonResponse({"state": 500, "message": "系统错误", "data": {}}, safe=False)
                        else:
                            return JsonResponse({"state": 500, "message": "注册失败", "data": user_info}, safe=False)
                    else:
                        return JsonResponse({"state": 500, "message": "未知管理员信息", "data": {}}, safe=False)
            else:
                return JsonResponse({"state": 500, "message": "请输入账号或密码", "data": {}}, safe=False)
        else:
            return JsonResponse({"state": 500, "message": "错误请求", "data": {}}, safe=False)
    except Exception as ex:
        print("create_common_user error")
        print(ex)
        return JsonResponse({"state": 500, "message": "服务器错误", "data": {}}, safe=False)


def get_user_msg(request):
    try:
        if request.method == 'GET':
            token = request.session.get("token")
            data = check_token(token)
            # 获取用户信息
            user_model = models.AdminUser.objects.get(pk=data["user_id"])
            user = model_to_dict(user_model)
            # 获取导航信息
            route_list = model_to_dict(user_model.permission)

            res = {"user": user["admin_user"], "route": route_list["menu_list"]}
            return JsonResponse({"state": 200, "message": "ok", "data": res}, safe=False)

        else:
            return JsonResponse({"state": 500, "message": "错误请求", "data": {}}, safe=False)
    except Exception as ex:
        print("get_user_msg error")
        print(ex)
        return JsonResponse({"state": 500, "message": "服务器错误", "data": {}}, safe=False)


def logout(request):
    try:
        if request.method == 'GET':
            request.session.flush()
            return JsonResponse({"state": 200, "message": "退出成功", "data": {}}, safe=False)
        else:
            return JsonResponse({"state": 500, "message": "错误请求", "data": {}}, safe=False)
    except Exception as ex:
        print("logout error")
        print(ex)
        return JsonResponse({"state": 500, "message": "服务器错误", "data": {}}, safe=False)
